<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <!-- Logo和身份标识 -->
          <div class="flex items-center gap-3">
            <div class="flex items-center gap-2">
              <div class="w-10 h-10 bg-blue-600 rounded-lg overflow-hidden">
                <img src="../../../头像.jpg" alt="头像" class="w-full h-full object-cover" />
              </div>
              <span class="text-xl font-semibold text-gray-900">校园快递代拿</span>
            </div>
            <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded">代拿员</span>
          </div>

          <!-- 右侧按钮 -->
          <HeaderActions />
        </div>
      </div>
    </header>

    <!-- 标签页导航 -->
    <nav class="bg-white border-b border-gray-200">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex gap-8">
          <button class="py-4 text-gray-600 hover:text-gray-900 border-b-2 border-transparent hover:border-gray-300" @click="$router.push('/courier/hall')">接单大厅</button>
          <button class="py-4 text-blue-600 border-b-2 border-blue-600 font-medium">我的订单</button>
          <button class="py-4 text-gray-600 hover:text-gray-900 border-b-2 border-transparent hover:border-gray-300" @click="$router.push('/courier/profile')">我的主页</button>
        </div>
      </div>
    </nav>

    <!-- 主要内容区域 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 页面标题和搜索 -->
      <div class="flex flex-wrap items-center justify-between mb-6">
        <h1 class="text-2xl font-bold text-gray-900">我的订单</h1>
        <div class="relative mt-4 sm:mt-0">
          <input v-model="searchKeyword" type="text" placeholder="搜索订单号、标题、地址" class="w-full sm:w-64 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
          <svg class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
          </svg>
        </div>
      </div>

      <!-- 订单状态筛选 -->
      <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="flex flex-wrap items-center gap-4">
          <span class="text-sm text-gray-600">订单状态:</span>
          <div class="flex flex-wrap gap-2">
            <button @click="filterStatus = 'all'" :class="{'bg-blue-600 text-white': filterStatus === 'all', 'text-gray-600 hover:bg-gray-100': filterStatus !== 'all'}" class="px-3 py-1 text-sm rounded">全部订单</button>
            <button @click="filterStatus = 'ongoing'" :class="{'bg-blue-600 text-white': filterStatus === 'ongoing', 'text-gray-600 hover:bg-gray-100': filterStatus !== 'ongoing'}" class="px-3 py-1 text-sm rounded">配送中</button>
            <button @click="filterStatus = 'picked'" :class="{'bg-blue-600 text-white': filterStatus === 'picked', 'text-gray-600 hover:bg-gray-100': filterStatus !== 'picked'}" class="px-3 py-1 text-sm rounded">已取件</button>
            <button @click="filterStatus = 'delivered'" :class="{'bg-blue-600 text-white': filterStatus === 'delivered', 'text-gray-600 hover:bg-gray-100': filterStatus !== 'delivered'}" class="px-3 py-1 text-sm rounded">已送达</button>
            <button @click="filterStatus = 'completed'" :class="{'bg-blue-600 text-white': filterStatus === 'completed', 'text-gray-600 hover:bg-gray-100': filterStatus !== 'completed'}" class="px-3 py-1 text-sm rounded">已完成</button>
            <button @click="filterStatus = 'cancelled'" :class="{'bg-blue-600 text-white': filterStatus === 'cancelled', 'text-gray-600 hover:bg-gray-100': filterStatus !== 'cancelled'}" class="px-3 py-1 text-sm rounded">已取消</button>
          </div>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="space-y-4">
        <div v-for="order in pagedOrders" :key="order.id" class="bg-white rounded-lg shadow-sm p-6">
          <!-- 订单头部 -->
          <div class="flex flex-wrap items-start justify-between mb-4">
            <div><span class="text-sm text-gray-600">订单编号: {{ order.id }}</span></div>
            <div class="flex items-center gap-4 mt-2 sm:mt-0">
              <span :class="getStatusBadgeClass(order.status)" class="px-2 py-1 text-xs rounded">{{ getStatusLabel(order.status) }}</span>
              <span class="text-sm text-gray-500">{{ order.time }}</span>
            </div>
          </div>

          <!-- 订单内容 -->
          <div class="mb-4">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">{{ order.title }}</h3>
            <div class="flex items-center gap-2">
              <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
              </svg>
              <span class="text-sm text-gray-600">{{ order.location }}</span>
            </div>
            <div class="flex items-center gap-2 mt-2">
              <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
              </svg>
              <span class="text-sm text-gray-600">下单者信用值: {{ order.rating }}</span>
            </div>
          </div>

          <!-- 订单底部 -->
          <div class="flex flex-wrap items-center justify-between pt-4 border-t border-gray-200">
            <div class="text-sm text-gray-600">订单金额</div>
            <div class="flex items-center gap-4 mt-3 sm:mt-0">
              <span class="text-xl font-bold text-gray-900">¥{{ order.price }}</span>
              <div class="flex gap-2">
                <button class="px-4 py-2 text-sm text-blue-600 border border-blue-600 rounded hover:bg-blue-50" @click="$router.push('/courier/order/detail/' + order.id)">查看详情</button>
                <button v-if="order.status === 'ongoing' || order.status === 'picked' || order.status === 'delivered'" @click="contactUser(order.id)" class="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700">联系用户</button>
                <button v-if="order.status === 'ongoing'" @click="cancelOrder(order.id)" class="px-4 py-2 text-sm border border-red-600 text-red-600 rounded hover:bg-red-50">取消接单</button>
                <button v-if="order.status === 'ongoing'" @click="markPickedUp(order.id)" class="px-4 py-2 text-sm border border-amber-600 text-amber-700 rounded hover:bg-amber-50">已取件</button>
                <button v-if="order.status === 'picked'" @click="markDelivered(order.id)" class="px-4 py-2 text-sm border border-green-600 text-green-700 rounded hover:bg-green-50">已送达</button>
                <button v-if="order.status === 'completed' && !order.rated" @click="$router.push('/courier/order/rate/' + order.id)" class="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700">评价用户</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="flex items-center justify-center gap-2 mt-8">
        <!-- 上一页 -->
        <button
          class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-white"
          :disabled="currentPage === 1"
          @click="currentPage > 1 && (currentPage -= 1)"
        >
          <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
          </svg>
        </button>

        <!-- 中间页码：1 ~ totalPages -->
        <button
          v-for="p in totalPages"
          :key="p"
          class="w-8 h-8 flex items-center justify-center rounded border"
          :class="p === currentPage ? 'bg-blue-600 text-white border-blue-600' : 'border-gray-300 text-gray-600 hover:bg-gray-100'"
          @click="currentPage = p"
        >
          {{ p }}
        </button>

        <!-- 下一页 -->
        <button
          class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-white"
          :disabled="currentPage === totalPages"
          @click="currentPage < totalPages && (currentPage += 1)"
        >
          <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
          </svg>
        </button>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 mt-8 py-6">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <p class="text-center text-gray-500 text-sm">© 2025 校园快递代拿系统 版权所有</p>
      </div>
    </footer>
  </div>
</template>

<script>
import axios from 'axios'
import HeaderActions from '../components/HeaderActions.vue'
export default {
  name: 'CourierOrderMy',
  components: { HeaderActions },
  data() {
    return {
      filterStatus: 'all',
      searchKeyword: '',
      orders: [],
      unread: 0,
      unreadTimer: null,
      currentPage: 1,
      pageSize: 10
    }
  },
  computed: {
    // 先根据状态和搜索关键字过滤出所有符合条件的订单
    filteredOrders() {
      let result = this.orders

      // 状态筛选
      if (this.filterStatus !== 'all') {
        result = result.filter(order => order.status === this.filterStatus)
      }

      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim().toLowerCase()
        result = result.filter(order => {
          const idStr = String(order.id || '').toLowerCase()
          const titleStr = String(order.title || '').toLowerCase()
          const locationStr = String(order.location || '').toLowerCase()
          return (
            idStr.includes(keyword) ||
            titleStr.includes(keyword) ||
            locationStr.includes(keyword)
          )
        })
      }

      return result
    },
    // 总页数（基于过滤后的结果动态计算）
    totalPages() {
      const total = this.filteredOrders.length
      if (total === 0) return 1
      return Math.ceil(total / this.pageSize)
    },
    // 当前页要展示的订单列表
    pagedOrders() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredOrders.slice(start, end)
    }
  },
  methods: {
    async fetchMyOrders() {
      const courierId = localStorage.getItem('userId')
      if (!courierId) {
        alert('请先登录');
        this.$router.push('/login');
        return;
      }
      try {
        const { data } = await axios.get(`/api/orders/courier/${courierId}`)
        const list = (data && (data.data || data)) || []
        this.orders = list.map(r => {
          // 状态映射（与后端保持一致）：1=待接单, 2=配送中, 3=已取件, 4=已送达, 5=已完成, 6=已取消
          let status = 'pending'
          const s = Number(r.status)
          if (s === 1) status = 'pending'
          else if (s === 2) status = 'ongoing'
          else if (s === 3) status = 'picked'      // 已取件
          else if (s === 4) status = 'delivered'   // 已送达
          else if (s === 5) status = 'completed'
          else if (s === 6) status = 'cancelled'
          
          return {
            id: r.id,
            title: r.pickup_code || `订单 #${r.id}`,
            pickup_code: r.pickup_code || '',
            location: r.pickup_location,
            price: Number((r.final_fee ?? r.suggested_fee ?? r.amount ?? r.fee ?? 0)).toFixed(2),
            rating: Number(r.orderer_credit || r.credit_score || r.rating || 0),
            status: status,
            time: (r.time || r.created_at || '').replace('T',' ').slice(0,19),
            rated: false
          }
        })
      } catch (e) {
        console.error('获取我的订单失败', e)
        alert('获取我的订单失败，请稍后再试')
      }
    },
    logout() {
      localStorage.removeItem('userToken')
      this.$router.push('/login')
    },
    getStatusLabel(status) {
      const statusMap = {
        'pending': '待接单',
        'ongoing': '配送中',
        'picked': '已取件',
        'delivered': '已送达',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    },
    getStatusBadgeClass(status) {
      const classMap = {
        'pending': 'bg-gray-100 text-gray-600',
        'ongoing': 'bg-yellow-100 text-yellow-700',
        'picked': 'bg-amber-100 text-amber-700',
        'delivered': 'bg-blue-100 text-blue-700',
        'completed': 'bg-green-100 text-green-700',
        'cancelled': 'bg-red-100 text-red-700'
      }
      return classMap[status] || 'bg-gray-100 text-gray-600'
    },
    async contactUser(orderId) {
      const me = Number(localStorage.getItem('userId'))
      if (!me) { this.$router.push('/login'); return }
      try {
        const { data } = await axios.get(`/api/orders/${orderId}`)
        const d = (data && data.data) || {}
        const ordererId = Number(d.orderer_user_id || 0)
        if (!ordererId) { alert('无法获取下单者信息'); return }
        const { data: created } = await axios.post('/api/messages/conversations', {
          participants: [me, ordererId],
          order_id: Number(orderId),
          type: 1
        })
        const cid = created && created.data && created.data.id
        this.$router.push({ path: '/messages', query: { cid } })
      } catch (e) {
        console.error('联系用户失败', e)
        alert('联系用户失败，请稍后再试')
      }
    },
    async rateUser(orderId) {
      const me = Number(localStorage.getItem('userId'))
      if (!me) { this.$router.push('/login'); return }

      const input = window.prompt('请给下单者打分（1-5）', '5')
      if (input === null) return
      const score = Number(input)
      if (!score || Number.isNaN(score) || score < 1 || score > 5) {
        alert('评分无效，请输入1到5之间的数字')
        return
      }

      try {
        const payload = { orderId: Number(orderId), courierId: me, score }
        const { data } = await axios.post('/api/users/order-users/rate', payload)
        if (data && data.success) {
          alert('评价已提交，感谢反馈')
          await this.fetchMyOrders()
        } else {
          alert(data && data.message ? data.message : '评价失败，请稍后再试')
        }
      } catch (e) {
        console.error('评价用户失败', e)
        alert('评价失败，请稍后再试')
      }
    },
    async cancelOrder(orderId) {
      const courierId = localStorage.getItem('userId')
      if (!courierId) { alert('请先登录'); this.$router.push('/login'); return }
      if (!confirm('确认取消该接单？')) return
      try {
        await axios.post(`/api/orders/${orderId}/cancel-by-courier`, { courier_user: Number(courierId) })
        await this.fetchMyOrders()
        alert('已取消接单')
      } catch (e) {
        console.error('取消接单失败', e)
        alert('取消接单失败，请稍后再试')
      }
    },
    async markPickedUp(orderId) {
      try {
        // 状态3表示"已取件"（与后端 PUT /api/orders/:id/status 保持一致）
        await axios.put(`/api/orders/${orderId}/status`, { status: 3 })
        await this.fetchMyOrders()
        alert('已标记为取件完成')
      } catch (e) {
        console.error('更新为已取件失败', e)
        alert('更新为已取件失败，请稍后再试')
      }
    },
    async markDelivered(orderId) {
      try {
        // 状态4表示"已送达"（注意：只有下单用户才能设置为"已完成"状态5）
        await axios.put(`/api/orders/${orderId}/status`, { status: 4 })
        await this.fetchMyOrders()
        alert('已标记为送达完成')
      } catch (e) {
        console.error('更新为已送达失败', e)
        alert('更新为已送达失败，请稍后再试')
      }
    }
  },
  mounted() {
    this.fetchMyOrders()
    const me = Number(localStorage.getItem('userId'))
    const tick = async () => {
      if (!me) return
      try {
        const { data } = await axios.get('/api/messages/unread-count', { params: { userId: me } })
        this.unread = (data && data.data && data.data.unread) || 0
      } catch {}
    }
    tick()
    this.unreadTimer = setInterval(tick, 10000)
  }
}
</script>

